package com.zyk;

import com.zyk.plugin.DispatcherTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.instrument.Instrumentation;
import java.util.Set;

public class Initializer {
    private static final Logger LOGGER = LoggerFactory.getLogger(Initializer.class);

    public static void init(Instrumentation inst, String appname, boolean mode) {
        // init env
        Environment env = Environment.getInstance();
        env.init(appname, mode);
        LOGGER.info(env.toString());


        // load plugins
        env.getPluginManager().loadPlugins(inst);

        // register transform and retransform loaded classes
        DispatcherTransformer dispatcherTransformer = env.getDispatcherTransformer();
        inst.addTransformer(dispatcherTransformer, true);
        inst.setNativeMethodPrefix(dispatcherTransformer, env.getNativePrefix());
        Set<String> classSet = dispatcherTransformer.getHookClassNames();
        for (Class<?> c : inst.getAllLoadedClasses()) {
            if (!classSet.contains(c.getName())) {
                continue;
            }
            try {
                c.getGenericSuperclass();
                inst.retransformClasses(c);
            } catch (Throwable e) {
                LOGGER.error("Retransform class failed: {}", c.getName(), e);
            }
        }
    }
}
